package com.tbgov.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.tbgov.entity.User;
import com.tbgov.entity.pojo.ResultPage;
import com.tbgov.service.IUserService;
import com.tbgov.util.MD5Util;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统后台用户表 前端控制器
 * </p>
 *
 * @author 1st
 * @since 2024-11-19
 */

@Tag(name = "系统后台用户管理", description = "系统后台用户相关接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/user/")
public class UserController {

    final IUserService userService;

    @Operation(summary = "新增或编辑系统后台用户")
    @PostMapping("addOrEdit")
    public ResponseEntity<Object> addOrEdit(@RequestBody User user){
        if (userService.count(Wrappers.<User>lambdaQuery().eq(User::getMobilePhone, user.getMobilePhone()).ne( user.getId() != null,User::getId, user.getId())) > 0) {
            return ResponseEntity.badRequest().body("手机号码已经存在不可新增或编辑");
        }
        user.setPwd(MD5Util.getMD5byBase64(user.getPwd()));
        userService.saveOrUpdate(user);
        return ResponseEntity.ok("success");
    }

    @Operation(summary = "删除系统后台用户 可单可批")
    @DeleteMapping("del")
    public ResponseEntity<Object> del(@RequestParam String ids){
        userService.removeBatchByIds(Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList()));
        return ResponseEntity.ok("success");
    }
    
    @Operation(summary = "获取系统后台用户列表")
    @GetMapping("list")
    @Parameters({
            @Parameter(name = "pageSize", description = "每页显示条数", required = true),
            @Parameter(name = "pageNum", description = "当前页码", required = true),
            @Parameter(name = "keyword", description = "关键字")
    })
    public ResponseEntity<ResultPage<User>> list(@RequestParam Integer pageSize, @RequestParam Integer pageNum, String keyword ){
        PageHelper.startPage(pageNum, pageSize);
        LambdaQueryWrapper<User> like = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(keyword)) {
            like.like(User::getName, keyword).or().like(User::getMobilePhone, keyword);
        }
        return ResponseEntity.ok(ResultPage.getList(userService.list(like)));
    }

}
